﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Collections;

namespace AutoPlayerNew
{
    public partial class TimingPlayer : Form
    {
        #region 初始化

        private int timeForHidden = 0;

        private string path = Application.StartupPath + "\\playlist.txt";

        public TimingPlayer()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.groupBoxList.SetBounds(12, 304, 500, 228);
            this.listView1.SetBounds(3, 315, 494, 208);
            this.axWindowsMediaPlayer1.SetBounds(12, 304, 500, 46);
            this.panelEdit.SetBounds(12, 304, 500, 90);
            this.timer1.Enabled = true;
            timeForHidden = 1;
            this.lblState.Text = "InitShow";
            this.lblTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            InitCbox();
            BintListViewForTime(OrderPlayList(), DateTime.Now.ToString("HH:mm:ss"));
            //MessageBox.Show("请在列表栏右键添加歌曲", "系统提示");
        }

        private void InitCbox()
        {
            this.cboxHour.SelectedIndex = 0;
            this.cboxMinute.SelectedIndex = 0;
            this.cboxSecond.SelectedIndex = 0;
        }

        private void ErrorMsg()
        {
            MessageBox.Show("文件读取出错，请重新添加", "系统提示");
            InitCbox();
            this.lblSongName.Text = "";
        }

        #endregion

        #region 面板动画

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (this.lblState.Text.Equals("InitShow"))
            {
                if (this.groupBoxList.Location.Y <= 12)
                {
                    this.timer1.Enabled = false;
                    return;
                }
                ShowGroupAndListView(timeForHidden);
                ShowAxPlayer(timeForHidden);
                timeForHidden++;
            }
            else if (this.lblState.Text.Equals("Edit"))
            {
                HiddenAxPlayer(2);
                ShowEditPanel(4, this.axWindowsMediaPlayer1.Location.Y);
            }
            else if (this.lblState.Text.Equals("ShowList"))
            {
                HiddenEditPlayer(4);
                ShowGroupAndListView();
                ShowAxPlayer(2,this.panelEdit.Location.Y);
            }
        }

        private void ShowGroupAndListView(int tfh)
        {
            this.groupBoxList.SetBounds(12, this.groupBoxList.Location.Y - tfh, 500, 228);
            this.listView1.SetBounds(3, this.listView1.Location.Y - tfh, 494, 208);
        }

        private void ShowAxPlayer(int tfh)
        {
            if (this.axWindowsMediaPlayer1.Location.Y > 246)
                this.axWindowsMediaPlayer1.SetBounds(12, this.axWindowsMediaPlayer1.Location.Y - tfh, 500, 46);
        }

        private void ShowAxPlayer(int tfh, int y)
        {
            if (y == 304)
            {
                if (this.axWindowsMediaPlayer1.Location.Y > 246)
                    this.axWindowsMediaPlayer1.SetBounds(12, this.axWindowsMediaPlayer1.Location.Y - tfh, 500, 46);
                else
                    this.timer1.Enabled = false;
            }
        }

        private void ShowEditPanel(int tfh)
        {
            if (this.panelEdit.Location.Y > 246)
                this.panelEdit.SetBounds(12, this.panelEdit.Location.Y - tfh, 500, 90);
        }

        private void ShowEditPanel(int tfh, int y)
        {
            if (y == 304)
            {
                if (this.panelEdit.Location.Y > 202)
                    this.panelEdit.SetBounds(12, this.panelEdit.Location.Y - tfh, 500, 90);
                else
                    this.timer1.Enabled = false;
            }
        }

        private void ShowGroupAndListView()
        {
            if (this.groupBoxList.Height < 228)
            {
                this.groupBoxList.Height++;
                this.listView1.Height++;
            }
        }

        private void HiddenEditPlayer(int tfh)
        {
            if (this.panelEdit.Location.Y < 304)
                this.panelEdit.SetBounds(12, this.panelEdit.Location.Y + tfh, 500, 90);
        }

        private void HiddenAxPlayer(int tfh)
        {
            if (this.axWindowsMediaPlayer1.Location.Y < 304)
                this.axWindowsMediaPlayer1.SetBounds(12, this.axWindowsMediaPlayer1.Location.Y + tfh, 500, 46);
            if (this.groupBoxList.Height > 184)
            {
                this.groupBoxList.Height--;
                this.listView1.Height--;
            }
        }

        #endregion

        #region ListView右键菜单

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            this.timer1.Enabled = true;
            this.lblState.Text = "Edit";
            this.lblSongName.Text = "";
            InitCbox();
            this.btnAdd.Enabled = true;
            this.btnUpdate.Enabled = false;
        }

        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            if (this.listView1.SelectedItems.Count > 0)
            {
                try
                {
                    this.timer1.Enabled = true;
                    this.lblState.Text = "Edit";
                    this.lblSongName.Text = this.listView1.SelectedItems[0].SubItems[2].Text;
                    string[] lines = File.ReadAllLines(path);
                    this.lblGuid.Text = this.listView1.SelectedItems[0].SubItems[0].Text;
                    for (int i = 0; i < lines.Length; i++)
                    {
                        string[] temp = lines[i].Split('|');
                        if (temp[0].Equals(this.lblGuid.Text))
                        {
                            this.cboxHour.SelectedItem = temp[2].Substring(0, 2);
                            this.cboxMinute.SelectedItem = temp[2].Substring(3, 2);
                            this.cboxSecond.SelectedItem = temp[2].Substring(6, 2);
                            break;
                        }
                    }
                    this.btnAdd.Enabled = false;
                    this.btnUpdate.Enabled = true;
                }
                catch
                {
                    File.Delete(path);
                    ErrorMsg();
                }
            }
        }

        private void toolStripMenuItem3_Click(object sender, EventArgs e)
        {

            if (this.listView1.SelectedItems.Count > 0)
            {
                int listIndex = this.listView1.SelectedItems[0].Index;
                string[] lines = File.ReadAllLines(path);
                int h = lines.Length-1;
                if (h > 0)
                {
                    string[] newLines = new string[h];
                    string guidId = this.listView1.Items[listIndex].SubItems[0].Text;
                    for (int i = 0; i < lines.Length; i++)
                    {
                        string[] temp = lines[i].Split('|');
                        int n = i;
                        if (temp[0].Equals(guidId))
                        {
                            for (int j = i + 1; j < lines.Length; j++)
                            {
                                newLines[n] = lines[j];
                                n++;
                            }
                            break;
                        }
                        newLines[n] = lines[i];
                    }

                    File.WriteAllLines(path, newLines);
                }
                else
                    File.WriteAllLines(path, new string[0]);
                this.listView1.Items.RemoveAt(listIndex);
            }
        }

        private void toolStripMenuItem4_Click(object sender, EventArgs e)
        {
            this.lblTimeState.Text = "all";
            BindListView(OrderPlayList());
            this.toolStripMenuItem4.Enabled = false;
            this.toolStripMenuItem5.Enabled = true;
        }

        private void toolStripMenuItem5_Click(object sender, EventArgs e)
        {
            this.lblTimeState.Text = "one";
            ListViewTime(DateTime.Now.ToString("HH:mm:ss"));
            this.toolStripMenuItem4.Enabled = true;
            this.toolStripMenuItem5.Enabled = false;
        }

        #endregion

        #region Panel添加、编辑歌曲

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.timer1.Enabled = true;
            this.lblState.Text = "ShowList";
        }

        private void btnSelectSong_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string FileName;

                FileInfo myFile = new FileInfo(openFileDialog1.FileName);
                FileName = myFile.Name; 
                string path = myFile.DirectoryName;
                this.lblSongName.Text = path + "\\" + FileName;
            }
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (this.lblSongName.Text.Length > 0)
            {
                string guid = Guid.NewGuid().ToString("N");
                string time = this.cboxHour.SelectedItem + "时" + this.cboxMinute.SelectedItem + "分" + this.cboxSecond.SelectedItem + "秒";
                try
                {
                    StreamWriter sw = new StreamWriter(path, true);
                    sw.WriteLine(guid + "|" + this.lblSongName.Text + "|" + time);
                    sw.Close();
                    BintListViewForTime(OrderPlayList(), DateTime.Now.ToString("HH:mm:ss"));
                    this.lblTimeState.Text = "one";
                    this.toolStripMenuItem4.Enabled = true;
                    this.toolStripMenuItem5.Enabled = false;
                    MessageBox.Show("添加成功", "系统提示");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "系统提示");
                }
            }
            else
                MessageBox.Show("请选择歌曲", "系统提示");
        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                string[] lines = File.ReadAllLines(path);
                for (int i = 0; i < lines.Length; i++)
                {
                    if (lines[i].Split('|')[0].Equals(this.lblGuid.Text))
                    {
                        lines[i] = this.lblGuid.Text + "|" + this.lblSongName.Text + "|" + this.cboxHour.SelectedItem + "时" + this.cboxMinute.SelectedItem + "分" + this.cboxSecond.SelectedItem + "秒";
                        break;
                    }
                }
                File.WriteAllLines(path, lines);
                BintListViewForTime(OrderPlayList(), DateTime.Now.ToString("HH:mm:ss"));
                this.lblTimeState.Text = "one";
                this.toolStripMenuItem4.Enabled = true;
                this.toolStripMenuItem5.Enabled = false;
                MessageBox.Show("编辑成功", "系统提示");

            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message, "系统提示");
            }
        }

        #endregion

        #region 数据绑定、Form关闭、任务栏菜单、时间控制

        private void BindListView(string[] al)
        {
            if (al.Length > 0)
            {
                try
                {
                    this.listView1.Items.Clear();
                    for (int i = 0; i < al.Length; i++)
                    {
                        string[] temp = al[i].ToString().Split('|');
                        int index = temp[1].LastIndexOf("\\") + 1;
                        ListViewItem lvi = new ListViewItem(new string[] { temp[0], temp[1].Substring(index, temp[1].Length - index), temp[1], temp[2] });
                        this.listView1.Items.Add(lvi);
                    }
                }
                catch
                {
                    File.Delete(path);
                    ErrorMsg();
                }
            }
        }

        private void BintListViewForTime(string[] al,string time)
        {

            if (al.Length > 0)
            {
                try
                {
                    this.listView1.Items.Clear();
                    for(int i=0;i<al.Length;i++)
                    {
                        string[] tempString=al[i].Split('|');
                        string temp = tempString[2];
                        DateTime lvTime = Convert.ToDateTime(temp);//Date = {2011-04-09 00:00:00}
                        DateTime newTime = Convert.ToDateTime(time);//newTime = {2011-04-09 18:53:12}
                        int ou = lvTime.CompareTo(newTime);
                        if (ou > 0)
                        {
                            TimeSpan ts = lvTime.Subtract(newTime);//{-18:51:31}
                            tempString[2] = (ts.Hours.ToString().Length == 1 ? ("0" + ts.Hours.ToString()) : ts.Hours.ToString()) + "时" + (ts.Minutes.ToString().Length == 1 ? ("0" + ts.Minutes.ToString()) : ts.Minutes.ToString()) + "分" + (ts.Seconds.ToString().Length == 1 ? ("0" + ts.Seconds.ToString()) : ts.Seconds.ToString()) + "秒";
                            int index = tempString[1].LastIndexOf("\\") + 1;
                            ListViewItem lvi = new ListViewItem(new string[] { tempString[0], tempString[1].Substring(index, tempString[1].Length - index), tempString[1], tempString[2] });
                            this.listView1.Items.Add(lvi);
                        }
                        //else if (ou == 0)
                        //{
                        //    lv.Items.Remove(lvi);
                        //    this.axWindowsMediaPlayer1.URL = al[1];
                        //    this.axWindowsMediaPlayer1.Ctlcontrols.play();
                        //}
                    }
                }
                catch
                {
                    File.Delete(path);
                    ErrorMsg();
                }
            }
        }

        private void ListViewTime(string time)
        {
            foreach (ListViewItem lvi in this.listView1.Items)
            {
                string timeOld = lvi.SubItems[3].Text;
                string filePath = lvi.SubItems[2].Text;
                DateTime lvTime = Convert.ToDateTime(timeOld);
                DateTime newTime = Convert.ToDateTime(time);
                int ou = lvTime.CompareTo(newTime);
                if (ou > 0)
                {
                    TimeSpan ts = lvTime.Subtract(newTime);
                    lvi.SubItems[3].Text = (ts.Hours.ToString().Length == 1 ? ("0" + ts.Hours.ToString()) : ts.Hours.ToString()) + "时" + (ts.Minutes.ToString().Length == 1 ? ("0" + ts.Minutes.ToString()) : ts.Minutes.ToString()) + "分" + (ts.Seconds.ToString().Length == 1 ? ("0" + ts.Seconds.ToString()) : ts.Seconds.ToString()) + "秒";
                }
                else if (ou == 0)
                {
                    this.listView1.Items.Remove(lvi);
                    this.axWindowsMediaPlayer1.URL = filePath;
                    this.axWindowsMediaPlayer1.Ctlcontrols.play();
                    this.timer1.Enabled = true;
                    this.lblState.Text = "ShowList";
                }
                else if (ou < 0)
                    this.listView1.Items.Remove(lvi);
            }
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            this.lblTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            if (this.lblTimeState.Text.Equals("one"))
            {
                ListViewTime("00:00:01");
                GC.Collect();
            }
        }

        private string[] OrderPlayList()
        {
            if (File.Exists(path))
            {
                try
                {
                    string[] lines = File.ReadAllLines(path);
                    for (int i = 0; i < lines.Length; i++)
                    {
                        for (int j = i + 1; j < lines.Length; j++)
                        {
                            string[] tempI = lines[i].Split('|');
                            string[] tempJ = lines[j].Split('|');
                            if (tempI[2].CompareTo(tempJ[2]) > 0)
                            {
                                string temp = lines[i];
                                lines[i] = lines[j];
                                lines[j] = temp;
                            }
                        }
                    }
                    return lines;
                }
                catch
                {
                    File.Delete(path);
                    ErrorMsg();
                    return new string[0];
                }
            }
            else
                return new string[0];
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            //Application.Exit();
        }

        private void Form1_SizeChanged(object sender, EventArgs e)
        {

            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Hide();
                this.notifyIcon1.Visible = true;
            }
        }

        private void toolStripMenuItem6_Click(object sender, EventArgs e)
        {

            this.Visible = true;
            this.WindowState = FormWindowState.Normal;
        }

        private void toolStripMenuItem7_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        #endregion

    }
}
